import tools from '../assets/js/tools'
import qs from 'qs'
import axios from 'axios'

let baseURL = ''
let isWeixin = navigator.userAgent.toLowerCase().indexOf('micromessenger') != -1;
if(isWeixin) {
  baseURL = 'http://treasure.jingyugg.com';   //微信
}else {
  baseURL = 'http://mobile.jingyugg.com';    //app
}

// axios 配置
axios.defaults.timeout = 10000;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';

//请求拦截器
axios.interceptors.request.use(
  config => {
    let token = tools.getCookie('token');
    if (token) {
      // 判断是否存在token，如果存在的话，则每个http header都加上token
      config.headers.token = `${token}`;
    }
    return config;
  },
  err => {
    return Promise.reject(err);
  });


export function post(url, params) {
  return new Promise((resolve, reject) => {
    axios.post(baseURL + url, qs.stringify(params))
      .then(response => {
        resolve(response.data);
      })
      .catch((error) => {
        reject(error)
      })
  })
}

export function get(url, params) {
  return new Promise((resolve, reject) => {
    axios.get(baseURL + url, {params: params})
      .then(response => {
        resolve(response.data);
      })
      .catch((error) => {
        reject(error)
      })
  })
}
